<template>
    <div class="interface-management">
      <!-- 搜索和新增按钮 -->
      <div class="header">
        <el-input v-model="params.interfacename" placeholder="请输入接口名称" style="width: 300px" />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="success" @click="handleAdd">新增接口</el-button>
      </div>
  
      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="interfacename" label="接口名称" />
        <el-table-column prop="description" label="接口描述" />
        <el-table-column prop="requestmethod" label="请求方法" />
        <el-table-column prop="requestpath" label="请求路径" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">修改</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          :current-page="params.pageNum"
          :page-size="params.pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
  
      <!-- 新增/修改弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
        <el-form :model="form" label-width="120px">
            <el-form-item label="接口名称">
                <el-input v-model="form.interfacename" />
            </el-form-item>
            <el-form-item label="接口描述">
                <el-input v-model="form.description" type="textarea" />
            </el-form-item>
            <el-form-item label="请求方法">
                <el-select v-model="form.requestmethod">
                    <el-option label="GET" value="GET" />
                    <el-option label="POST" value="POST" />
                    <el-option label="PUT" value="PUT" />
                    <el-option label="DELETE" value="DELETE" />
                </el-select>
            </el-form-item>
            <el-form-item label="请求路径">
                <el-input v-model="form.requestpath" />
            </el-form-item>
            <el-form-item label="SQL查询">
                <el-input v-model="form.sqlquery" type="textarea" rows="6" />
            </el-form-item>
            <el-form-item label="状态">
                <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
            </el-form-item>
            <!-- 新增查询条件输入区域 -->
            <el-form-item label="查询条件">
                <el-row v-for="(condition, index) in form.conditions" :key="index">
                    <el-col :span="10">
                        <el-input v-model="condition.key" placeholder="条件名" />
                    </el-col>
                    <el-col :span="10">
                        <el-input v-model="condition.value" placeholder="条件值" />
                    </el-col>
                </el-row>
                <el-button @click="addCondition">新增条件</el-button>
            </el-form-item>
            <!-- 新增 pageNum 和 pageSize 输入框 -->
            <el-form-item label="页码">
                <el-input v-model="testParams.pageNum" type="number" />
            </el-form-item>
            <el-form-item label="每页数量">
                <el-input v-model="testParams.pageSize" type="number" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <!-- 新增测试按钮 -->
            <el-button type="info" @click="handleTest">测试</el-button>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
        </template>
    </el-dialog>

  
  <!-- 测试结果弹窗 -->
  <el-dialog v-model="testDialogVisible" title="测试结果" width="80%" class="fixed-size-dialog"  @close="resetTestParams">
         
            <el-table :data="testTableData" border style="width: 100%">
                <template v-for="(column, index) in testColumns" :key="index">
                    <el-table-column :prop="column" :label="column" />
                </template>
            </el-table>
            <!-- 添加新的类名 pagination-center -->
            <div class="pagination pagination-center">
                <el-pagination
                    :current-page="testParams.pageNum"
                    :page-size="testParams.pageSize"
                    :total="testTotal"
                    layout="total, prev, pager, next, jumper"
                    @current-change="handleTestPageChange"
                    @size-change="handleTestSizeChange"
                />
            </div>
        
        <template #footer>
            <el-button @click="testDialogVisible = false">关闭</el-button>
        </template>
    </el-dialog>

    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import { ElForm, ElFormItem, ElInput, ElButton,ElMessage  } from 'element-plus';
  import axios from 'axios';
  import request from '../utils/request';
  
  // 表格数据
  const tableData = ref([]);
  //const searchKeyword = ref('');
  const currentPage = ref(1);
  //const pageSize = ref(10);
  const total = ref(0);
  
  // 弹窗相关
  const dialogVisible = ref(false);
  const dialogTitle = ref('新增接口');
  const form = ref({
    interfacename: '',
    description: '',
    requestmethod: 'POST',
    requestpath: '',
    sqlquery: '',
    status: 1,
    conditions: [
            { key: '', value: '' }
        ]
  });
  const isEditMode = ref(false); // 是否为编辑模式

    // 查询参数
    const params = ref({
    interfacename: '',
    pageNum: 1,
    pageSize: 14,
    });

    // 测试相关
const testDialogVisible = ref(false);
const testTableData = ref([]);
const testColumns = ref([]);
const testTotal = ref(0);
const testParams = ref({
    pageNum: 1,
    pageSize: 10,
});

// 新增查询条件
const addCondition = () => {
    if (!form.value.conditions) {
        form.value.conditions = [];
    }
    form.value.conditions.push({ key: '', value: '' });
};

    // 分页大小改变
    const handleSizeChange = (size) => {
        params.value.pageSize = size;
        fetchData();
    };

    // 分页页码改变
    const handlePageChange = (page) => {
        params.value.pageNum = page;
        fetchData();
    };
  
  // 获取数据
  const fetchData = async () => {
    try {
      const res = await request.post('/sys/datainterface/queryByPage',params.value);
      tableData.value = res.data.records;
      total.value = res.data.total;
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  };
  
  // 搜索
  const handleSearch = () => {
    currentPage.value = 1;
    fetchData();
  };
  
  // 新增
  const handleAdd = () => {
    dialogTitle.value = '新增接口';
    isEditMode.value = false;
    form.value = {
      interfacename: '',
      description: '',
      requestmethod: 'POST',
      requestpath: '',
      sqlquery: '',
      status: 1,
      conditions: [
        { key: '', value: '' }
        ],
    };
    dialogVisible.value = true;
  };
  
  // 修改
  const handleEdit = (row) => {
    dialogTitle.value = '修改接口';
    isEditMode.value = true;
    form.value = { ...row };
    dialogVisible.value = true;
  };
  
  // 删除
  const handleDelete = async (id) => {
    try {
        debugger;
        const res = await request.post('/sys/datainterface/delete', {"id":id});
      ElMessage.success('删除成功');
      fetchData();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  };
  
  // 提交表单
  const handleSubmit = async () => {
    try {
      if (isEditMode.value) {
        const res = await request.post('/sys/datainterface/update', form.value);
        ElMessage.success('修改成功');
      } else {
        const res = await request.post('/sys/datainterface/add', form.value);
        ElMessage.success('新增成功');
      }
      dialogVisible.value = false;
      fetchData();
    } catch (error) {
      console.error('提交失败:', error);
      ElMessage.error('提交失败');
    }
  };

  // 重置测试相关参数
const resetTestParams = () => {
    testTableData.value = [];
    testColumns.value = [];
    testTotal.value = 0;
    testParams.value = {
        pageNum: 1,
        pageSize: 10,
    };
};

  // 测试按钮点击事件
const handleTest = async () => {
    const testData = {
        pageNum: Number(testParams.value.pageNum),
        pageSize: Number(testParams.value.pageSize),
        sqlquery: form.value.sqlquery,
        interfacename: form.value.interfacename,
        // realname: "周彤",
        // gender: "男",
        // 拼接查询条件
        
    };

     // 检查 conditions 是否存在且不为空数组
    if (form.value.conditions && form.value.conditions.length > 0) {
        // 将输入的查询条件拼接到 testData 中
        form.value.conditions.forEach(condition => {
            if (condition.key && condition.value) {
                testData[condition.key] = condition.value;
            }
        });
    }

    try {
        const res = await request.post('/sys/datainterface/testquerySql', testData);
        debugger;
        if (res.data.records.length > 0) {
            testTableData.value = res.data.records;
            testTotal.value = res.data.total;
            
            // 动态获取列名
            if (res.data.records.length > 0) {
                testColumns.value = Object.keys(res.data.records[0]);
            }
            testDialogVisible.value = true; 
        } else {
            ElMessage.info('未查询到数据');
        }
    } catch (error) {
        console.error('测试查询失败:', error);
        ElMessage.error('测试查询失败');
    }
};

// 测试结果分页大小改变
const handleTestSizeChange = (size) => {
    testParams.value.pageSize = size;
    handleTest();
};

// 测试结果分页页码改变
const handleTestPageChange = (page) => {
    testParams.value.pageNum = page;
    handleTest();
};
  
  // 初始化加载数据
  onMounted(() => {
    fetchData();
  });
  </script>
  
  <style scoped>
  .interface-management {
    padding: 20px;
  }
  
  .header {
    margin-bottom: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .fixed-size-dialog .el-dialog__body {
    max-height: 400px; /* 设置最大高度，可根据需要调整 */
    overflow-y: auto; /* 内容超过高度时显示垂直滚动条 */
}
 
  </style>